package com.joint.base.util;

import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Maps;
import com.joint.base.parent.BaseFlowEntity;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FileUtils;
import org.hibernate.SessionFactory;
import org.hibernate.persister.entity.AbstractEntityPersister;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by hpj on 2014/8/5.
 */
public class WorkflowUtils {
    /**
     * 转换流程节点类型为中文说明
     *
     * @param type 英文名称
     * @return 翻译后的中文名称
     */
    public static String parseToZhType(String type) {
        Map<String, String> types = new HashMap<String, String>();
        types.put("userTask", "用户任务");
        types.put("serviceTask", "系统任务");
        types.put("startEvent", "开始节点");
        types.put("endEvent", "结束节点");
        types.put("exclusiveGateway", "条件判断节点(系统自动根据条件处理)");
        types.put("inclusiveGateway", "并行处理任务");
        types.put("callActivity", "子流程");
        return types.get(type) == null ? type : types.get(type);
    }


    /**
     * 导出图片文件到硬盘
     *
     * @return 文件的全路径
     */
    public static String exportDiagramToFile(RepositoryService repositoryService, ProcessDefinition processDefinition, String exportDir) throws IOException {
        String diagramResourceName = processDefinition.getDiagramResourceName();
        String key = processDefinition.getKey();
        int version = processDefinition.getVersion();
        String diagramPath = "";

        InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), diagramResourceName);
        byte[] b = new byte[resourceAsStream.available()];

        @SuppressWarnings("unused")
        int len = -1;
        resourceAsStream.read(b, 0, b.length);

        // create file if not exist
        String diagramDir = exportDir + "/" + key + "/" + version;
        File diagramDirFile = new File(diagramDir);
        if (!diagramDirFile.exists()) {
            diagramDirFile.mkdirs();
        }
        diagramPath = diagramDir + "/" + diagramResourceName;
        File file = new File(diagramPath);

        // 文件存在退出
        if (file.exists()) {
            // 文件大小相同时直接返回否则重新创建文件(可能损坏)
            return diagramPath;
        } else {
            file.createNewFile();
        }


        // wirte bytes to file
        FileUtils.writeByteArrayToFile(file, b);
        return diagramPath;
    }

    //取表，实体
    public static Map<String,Object> initMappings(SessionFactory sessionFactory){
        Map<String,Object> mappings = Maps.newHashMap();
//            idMappings = new HashMap<String, String>();
        Map metaMap = sessionFactory.getAllClassMetadata();
        for (String key : (Set<String>) metaMap.keySet()) {
            AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap
                    .get(key);
            String tableName = classMetadata.getTableName().toLowerCase();
            int index = tableName.indexOf(".");
            if (index >= 0) {
                tableName = tableName.substring(index + 1);
            }
            String className = classMetadata.getEntityMetamodel().getName();
            String idName = classMetadata.getIdentifierColumnNames()[0];
            //根据表名返回实体名
            mappings.put(tableName, className);
            //根据实体返回表名
//                idMappings.put(className, idName);
        }
        return mappings;
    }

    /**
     * 根据实体类获得模块的名字
     * @param entity
     * @return
     */
    public static String getModularName(BaseFlowEntity entity){
        if(entity == null){
            return null;
        }
        String[] manage ={"notice","schedule","dispatch","receive","meetingleave","meetingsign","meetinguse","registe","meetingrecord","taskcontrol","taskback",
                "qualifications","seal","worklog","car","oil","oilquery","contract","purchase","assetuse","usedetail","assetscrap","reception","carconfig","qualificationsdict"};
        String[] party ={"strongbig","selectionnotice","selectionapply",
                "selectionspeech","selectionpublicity","selectionissued","activitymanager",
                "moneymanager","moneyManagerdetail","moneyavg","moneyavgdetail","letterregister",
                "annualbudget","annualbudgetdetail","rebateactivity","rebateactivitydetail","partymoney"};
        String[] finance ={"finance","calculationyear","modifyyear","newsmonth","financeyear",
                "financialanalysis","workplan","auditnotice","auditfirst","auditlast","auditedit","auditanswer",
                "expend"};
        String className = entity.getClass().getName().toLowerCase();
        className =  className.substring(className.lastIndexOf(".")+1);
        LogUtil.info("className:"+className);
        if(Arrays.asList(manage).contains(className)){
            return "行政管理";
        }else if(Arrays.asList(party).contains(className)){
            return "党政管理";
        }else if(Arrays.asList(finance).contains(className)){
            return "财务管理";
        }else{
            return "人事管理";
        }
    }


    public static boolean httpDownload(String httpUrl,String saveFile){
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = null;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(saveFile);

            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
